//
//  UnderViewController.m
//  SmileRead
//
//  Created by dllo on 15/8/21.
//  Copyright (c) 2015年 JIZ. All rights reserved.
//

#import "UnderViewController.h"
#import "LeftSlideViewController.h"
#import "DramerPersonViewController.h"
#import "Path.h"
#import "AppDelegate.h"
#import "Mybutton.h"
#import "CollectionMainViewController.h"
#import "FileNameList.h"
#import "DramerPersonViewController.h"
#import "NightSingleton.h"
#import "DrawerTableViewCell.h"

@interface UnderViewController () <UITableViewDataSource, UITableViewDelegate, DramerPersonViewControllerDelegate>

{
    float _cacheSize;
}

@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) LeftSlideViewController *drawer;

@property (nonatomic, retain) UIImageView *backImage;

@property (nonatomic, retain) UIImageView *personImage;

@property (nonatomic, retain) UILabel *nameLabel;

// 用于清除缓存
@property (nonatomic, retain) NSArray *arrayOfCache;

@property (nonatomic, retain) NSArray *arrayOfFunction;

// 用来判断夜间模式的切换
@property (nonatomic, assign) BOOL change;

@property (nonatomic, retain) UIView *nightView;

@property (nonatomic, retain) NSArray *array;

@end

@implementation UnderViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.nightView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        self.nightView.backgroundColor = [UIColor blackColor];
        self.nightView.userInteractionEnabled = NO;
        self.nightView.alpha = 0.6;
        
        self.arrayOfCache = @[FILE_Jokes, FILE_LY_VoiceOfMusic, FILE_Read, FILE_ReadOfHeader, FILE_ReadOfSecond, FILE_Voice];
        self.arrayOfFunction = @[@"个人设置", @"个人收藏", @"清除缓存", @"夜间模式", @"删除日记", @"关于我们"];
        self.array = @[@"person.png", @"collected.png", @"swap.png", @"night.png", @"riji.png", @"women.png"];
    }
    return self;
}

- (void)dealloc
{
    [_arrayOfFunction release];
    [_nameLabel release];
    [_personImage release];
    [_backImage release];
    [_drawer release];
    [_tableView release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
//    self.personImage.image = [UIImage imageWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"image"]];
    
    NSString *str = [Path pathOfLibraryWithFileName:LY_Image];
    self.personImage.image = [UIImage imageWithContentsOfFile:str];
    
    
    self.nameLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"name"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createBackground];
    [self createTableView];
   
}

- (void)createBackground
{
    self.backImage = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.backImage.userInteractionEnabled = YES;
    self.backImage.image = [UIImage imageWithContentsOfFile:[Path pathOfImageWithName:@"6.jpg"]];
    [self.view addSubview:self.backImage];
    [_backImage release];
}

// 创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    [self createHeaderFooterView];
    [_tableView release];
    
}

- (void)createHeaderFooterView
{
    
    UIView *headreView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 130 * heightFit)] autorelease];
    //headreView.backgroundColor = [UIColor grayColor];
    
    headreView.backgroundColor = [Path colorWithRed:64 green:70 blue:77];
    
    self.tableView.tableHeaderView = headreView;
    
    self.personImage = [[UIImageView alloc] initWithFrame:CGRectMake(15 * widthFit, 25, 50 * widthFit, 50 * widthFit)];
    self.personImage.layer.cornerRadius = self.personImage.frame.size.height / 2;
    self.personImage.layer.masksToBounds = YES;
    self.personImage.backgroundColor = [UIColor cyanColor];
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(50 * widthFit, 80 * heightFit, 100 * widthFit, 40 * widthFit)];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"name"]) {
        self.nameLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"name"];
    }
    else {
        self.nameLabel.text = @"Sponge";
    }
    
    
    
    [headreView addSubview:self.nameLabel];
    [headreView addSubview:self.personImage];
    [_personImage release];
    [headreView release];
    
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 80 * heightFit)];
    //footView.backgroundColor = [UIColor grayColor];
    footView.backgroundColor = [UIColor colorWithRed:64 / 255.0 green:70 / 255.0 blue:77 / 255.0 alpha:1];
    self.tableView.tableFooterView = footView;
    [footView release];
}

- (void)personEdit:(Mybutton *)button
{
    DramerPersonViewController *person = [[DramerPersonViewController alloc] init];

        // 点击跳转到下一界面
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppDelegate.window.rootViewController presentViewController:person animated:YES completion:^{
        }];
}

// 接收抽屉

- (void)receiveWithDrawer:(LeftSlideViewController *)drawer
{
    self.drawer = drawer;
}

#pragma mark - 协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayOfFunction.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ident = @"cell";
    DrawerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];
    if (cell == nil) {
        cell = [[[DrawerTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ident] autorelease];
    }
    if (indexPath.row == 0) {
        [cell receiveImageName:self.array[indexPath.row] title:self.arrayOfFunction[indexPath.row]];
    }
    if (indexPath.row == 1) {
        [cell receiveImageName:self.array[indexPath.row] title:self.arrayOfFunction[indexPath.row]];

    }
    if (indexPath.row == 2) {
        [cell receiveImageName:self.array[indexPath.row] title:self.arrayOfFunction[indexPath.row]];

    }
    if (indexPath.row == 3) {
        [cell receiveImageName:self.array[indexPath.row] title:self.arrayOfFunction[indexPath.row]];

    }
    if (indexPath.row == 4) {
        [cell receiveImageName:self.array[indexPath.row] title:self.arrayOfFunction[indexPath.row]];
    }
    if (indexPath.row == 5) {
        [cell receiveImageName:self.array[indexPath.row] title:self.arrayOfFunction[indexPath.row]];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60 * heightFit;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [self.drawer closeLeftView];
    if (self.drawer.closed) {
        if (indexPath.row == 0) {
            DramerPersonViewController *persion = [[DramerPersonViewController alloc] init];
            persion.delegate = self;
            AppDelegate *tempAppdelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            [tempAppdelegate.window.rootViewController presentViewController:persion animated:YES completion:^{
            }];
        }
        
        if (indexPath.row == 1) {
            CollectionMainViewController *collection = [[CollectionMainViewController alloc] init];
            AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            [tempAppDelegate.window.rootViewController presentViewController:collection animated:YES completion:^{
                
            }];
        }
        
        if (indexPath.row == 2) {
            [self swapCache];
        }
        if (indexPath.row == 3) {
            [self changeOfstatus];
        }
        if (indexPath.row == 4) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"删除心情日记" message:@"你若安好, 便是晴天" preferredStyle:UIAlertControllerStyleAlert];
            AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            
            [tempAppDelegate.window.rootViewController presentViewController:alert animated:YES completion:^{
                
            }];
            
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                [self deleteOfnote];
            }];
            
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                
            }];
            [alert addAction:action2];
            [alert addAction:action1];
        }
        
    }
    if (indexPath.row ==5) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"关于我们" message:@"目前版本:1.0" preferredStyle:UIAlertControllerStyleAlert];
        AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:action];
        [tempAppDelegate.window.rootViewController presentViewController:alert animated:YES completion:nil];
    }
}

// 删除日记

- (void)deleteOfnote
{
    NSFileManager *file = [NSFileManager defaultManager];
    NSString *path = [Path pathOfLibraryWithFileName:FILE_Note];
    if ([file fileExistsAtPath:path]) {
        [file removeItemAtPath:path error:nil];
    }
}



// 清除缓存
- (void)swapCache
{
    _cacheSize = [self calculateCache];
    NSString *string = [NSString stringWithFormat:@"您的缓存%fM", _cacheSize];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"清除缓存" message:string preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSFileManager *file = [NSFileManager defaultManager];
        // 遍历文件并进行删除
        for (int i = 0; i < self.arrayOfCache.count; i++) {
            NSString *path = [Path pathOfLibraryWithFileName:self.arrayOfCache[i]];
            if ([file fileExistsAtPath:path]) {
                [file removeItemAtPath:path error:nil];
            }
        }
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppDelegate.window.rootViewController presentViewController:alert animated:YES completion:nil];
}

- (float)calculateCache
{
    float cache = 0;
    for (int i = 0; i < self.arrayOfCache.count; i++) {
        NSString *path = [Path pathOfLibraryWithFileName:self.arrayOfCache[i]];
        NSFileManager *file = [NSFileManager defaultManager];
        if ([file fileExistsAtPath:path]) {
            cache += [[file attributesOfItemAtPath:path error:nil] fileSize];
        }
    }
    return cache / (1024 * 1024);
}


// 夜间模式的切换
- (void)changeOfstatus
{
#if 1
    self.change = !self.change;
        if (self.change) {
        AppDelegate *tempAppdelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [tempAppdelegate.window addSubview:self.nightView];
    }
    else {
        [self.nightView removeFromSuperview];
    }
#endif
    
}


// 实现协议方法DramerPersonViewControllerDelegate
- (void)sendWithUserInfo:(NSUserDefaults *)userInfo
{
    NSDictionary *dic = [userInfo objectForKey:LY_PERSON];
    if ([dic objectForKey:@"name"]) {
        self.nameLabel.text = [dic objectForKey:@"name"];
    }
    NSString *str = [Path pathOfLibraryWithFileName:LY_Image];
    self.personImage.image = [UIImage imageWithContentsOfFile:str];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
